<?php
declare(strict_types=1);

namespace app\api\logic;

use app\admin\model\article\Article;
use app\admin\model\user\Vip;
use app\admin\model\user\UserVipCard;
use app\basic\BaseLogic;
use app\admin\model\order\Order;
use app\admin\model\order\OrderGoods;
use think\facade\Db;

class OrderLogic extends BaseLogic
{
    protected $orderGoodsModel;

    protected $error;

    public function __construct()
    {
        $this->model = new Order();
        $this->orderGoodsModel = new OrderGoods();
    }

     /**
     * 创建订单
     * @param int $userId 用户ID
     * @param array $params 订单参数
     * @return array|bool
     */
    public function getCreateOrderInfo($userId, $params)
    {
        // 参数验证
        $validate = new \think\Validate();
        $validate->rule([
            'goods_id' => 'require|number',
            'total_num' => 'require|number|gt:0',
        ]);
        if (!$validate->check($params)) {
            $this->setError($validate->getError());
            return false;
        }
        // 获取商品信息
        $goods = (new Article())->where("id",$params['goods_id'])->find();
        if (empty($goods)) {
            $this->setError('文档不存在');
            return false;
        }
        // 计算订单金额
        $totalPrice = bcmul($goods['price'], $params['total_num'], 2);
        $payPrice = $totalPrice;
        // // 处理优惠券
        // if (!empty($params['coupons_id'])) {
        //     // TODO: 优惠券逻辑处理
        // }
       // 获取用户会员信息
        $memberInfo = $this->getMemberInfo($userId);
        // 计算会员折扣
        if (!empty($memberInfo) && $memberInfo['status'] == 1) {
            // 获取折扣比例 (例如: 95折 = 0.95)
            $discount = bcdiv($memberInfo['discount_number'], "10", 2);
            // 计算折扣后价格
            $payPrice = bcmul($payPrice, $discount, 2);
        }
        return [
            'pay_price' => $payPrice
        ];
    }

    /**
     * 创建订单
     * @param int $userId 用户ID
     * @param array $params 订单参数
     * @return array|bool
     */
    public function createOrder($userId, $params)
    {
        // 参数验证
        $validate = new \think\Validate();
        $validate->rule([
            'goods_id' => 'require|number',
            'total_num' => 'require|number|gt:0',
            'pay_type' => 'require|in:1,2,3',
            'client_type' => 'number',
            'coupons_id' => 'number'
        ]);
        if (!$validate->check($params)) {
            $this->setError($validate->getError());
            return false;
        }
        // 获取商品信息
        $goods = (new Article())->where("id",$params['goods_id'])->find();
        if (empty($goods)) {
            $this->setError('文档不存在');
            return false;
        }
        // 开启事务
        Db::startTrans();
        try {
            // 计算订单金额
            $totalPrice = bcmul($goods['price'], $params['total_num'], 2);
            $payPrice = $totalPrice;
            // 处理优惠券
            if (!empty($params['coupons_id'])) {
                // TODO: 优惠券逻辑处理
            }
           // 获取用户会员信息
           $memberInfo = $this->getMemberInfo($userId);
            // 计算会员折扣
            if (!empty($memberInfo) && $memberInfo['status'] == 1) {
                // 获取折扣比例 (例如: 95折 = 0.95)
                $discount = bcdiv($memberInfo['discount_number'], "100", 2);
                // 计算折扣后价格
                $payPrice = bcmul($payPrice, $discount, 2);
            }
            // 生成订单号
            $orderNo = generateOrderNo();
            // 创建订单
            $order = [
                'order_no' => $orderNo,
                'total_price' => $totalPrice,
                'pay_price' => $payPrice,
                'pay_status' => 10, // 未付款
                'user_id' => $userId,
                'create_time' => time(),
                'update_time' => time(),
                'order_type' => 1, // 普通订单
                'pay_type' => $params['pay_type'],
                'client_type' => $params['client_type'] ?? 1,
                'coupons_id' => $params['coupons_id'] ?? 0,
                'order_status' => 10 // 正常
            ];
            if (!$orderId = $this->model->insertGetId($order)) {
                throw new \Exception('创建订单失败');
            }
            // 创建订单商品
            $orderGoods = [
                'goods_id' => $goods['id'],
                'goods_name' => $goods['title'],
                'image' => '',
                'content' => '',
                'goods_price' => $goods['price'],
                'total_num' => $params['total_num'],
                'total_price' => $totalPrice,
                'order_id' => $orderId,
                'member_id' => $userId,
                'create_time' => time()
            ];
            if (!$this->orderGoodsModel->insert($orderGoods)) {
                throw new \Exception('创建订单商品失败');
            }
            // 提交事务
            Db::commit();
            return [
                'order_id' => $orderId,
                'order_no' => $orderNo,
                'pay_price' => $payPrice
            ];
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $this->setError($e->getMessage());
            return false;
        }
    }

    /**
     * 获取用户会员信息
     * @param int $userId 用户ID
     * @return array|null
     */
    protected function getMemberInfo($userId)
    {
        // 从会员表获取信息
        $memberInfo = (new UserVipCard())->where(['user_id' => $userId])->find();
        if (empty($memberInfo)) {
            return null;
        }
        // 判断会员是否有效
        $status = $memberInfo['end_time'] > time() ? 1 : 0;
        return [
            'status' => $status,                    // 会员状态：1=有效 0=过期
            'discount_number' => $memberInfo['discount_number'] ?? 100,  // 折扣比例，默认100(不打折)
            'expire_time' => $memberInfo['end_time']
        ];
    }

     /**
     * 创建会员卡订单
     * @param int $userId
     * @param array $params
     * @return array|bool
     */
    public function createVipOrder($userId, $params)
    {
        Db::startTrans();
        try {
            // 获取会员卡信息
            $cardInfo = (new Vip())->where("id",$params['card_id'])->find();
            if (!$cardInfo) {
                $this->setError('会员卡不存在');
                return false;
            }
            // 计算支付金额
            $payPrice = $cardInfo['price'];
            // 生成订单号
            $orderNo = generateOrderNo();
            // 创建订单主表数据
            $orderData = [
                'order_no' => $orderNo,
                'total_price' => $cardInfo['price'],
                'pay_price' => $payPrice,
                'pay_status' => 10,
                'user_id' => $userId,
                'create_time' => time(),
                'update_time' => time(),
                'order_type' => 2, // 会员卡订单
                'pay_type' => $params['pay_type'],
                'client_type' => $params['client_type'],
                'order_status' => 10,
                'coupons_id' => $params['coupons_id'] ?? 0
            ];
            // 创建订单
            $order = $this->model->create($orderData);
            // 创建订单商品
            $orderGoodsData = [
                'goods_id' => $params['card_id'],
                'goods_name' => $cardInfo['name'],
                'image' =>'',
                'content' =>'',
                'goods_price' => $cardInfo['price'],
                'total_num' => 1,
                'total_price' => $cardInfo['price'],
                'order_id' => $order['order_id'],
                'member_id' => $userId,
                'create_time' => time()
            ];

            $this->orderGoodsModel->create($orderGoodsData);

            Db::commit();

            // 返回订单信息
            return [
                'order_id' => $order['order_id'],
                'order_no' => $orderNo,
                'pay_price' => $payPrice,
                'pay_type' => $params['pay_type']
            ];
        } catch (\Exception $e) {
            Db::rollback();
            $this->setError($e->getMessage());
            return false;
        }
    }


      /**
     * 获取购买记录列表
     * @param int $userId
     * @param array $params
     * @return array|bool
     */
    public function getPurchaseList($userId, $params = [])
    {
        try {
            $page = !empty($params['page']) ? intval($params['page']) : 1;
            $limit = !empty($params['limit']) ? intval($params['limit']) : 10;
            // 构建查询
            $query = $this->model->alias('o')
                ->join('order_goods og', 'o.order_id = og.order_id')
                ->join('article a', 'og.goods_id = a.id')
                ->where([
                    'o.user_id' => $userId,
                    'o.order_type' => 1,  // 普通商品订单
                    'o.order_status' => 10, // 正常订单,
                    'o.pay_status' => 20,
                ])
                ->field([
                    'o.order_id',
                    'o.order_no',
                    'o.pay_price',
                    'o.pay_time',
                    'o.pay_status',
                    'a.title',
                    'a.filesize',
                    'a.file_type',
                    'a.fileext'
                ]);

            // 获取总数
            $total = $query->count();

            // 获取列表
            $list = $query->page($page, $limit)
                ->order('o.create_time DESC')
                ->select()
                ->each(function($item) {
                    // 格式化数据
                    $item['status'] = $item['pay_status'];
                    unset($item['pay_status']);
                    return $item;
                })
                ->toArray();

            return [
                'total' => $total,
                'list' => $list
            ];

        } catch (\Exception $e) {
             $this->setError($e->getMessage());
             return false;
        }
    }

     /**
     * 获取订单统计
     * @param int $userId
     * @return array|bool
     */
    public function getOrderStats($userId)
    {
        try {
            // 基础查询条件
            $where = [
                'user_id' => $userId,
                'order_status' => 10, // 正常订单
                'pay_status' => 20    // 已支付订单
            ];

            // 总消费金额（已支付订单）
            $totalAmount = $this->model
                ->where($where)
                ->sum('pay_price');

            // 订单数量统计（已支付订单）
            $totalOrders = $this->model
                ->where($where)
                ->count();

            return [
                'total_amount' => number_format($totalAmount, 2),
                'total_orders' => $totalOrders
            ];

        } catch (\Exception $e) {
             $this->setError($e->getMessage());
             return false;
        }
    }


    public function setError($error)
    {
        $this->error = $error;
    }

    public function getError()
    {
        return $this->error;
    }

}